﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.CardInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
/**
 * 激活卡片
 * @author kuanter
 *
 */
public class ActivateCardActivity extends WuyangBaseActivity implements
		OnClickListener {
	private Intent intent = new Intent();
	private Button activate_card_next_btn;
	private TextView send_auth_code_btn;
	private EditText account_number_et;
	private EditText confirm_account_number_et;
	private EditText phone_nubmer_et;
	private String account_number;
	private String confirm_account_number;
	private String phone_nubmer;
	private EditText auth_code_et;
	private String auth_code;
	private String createAuthCode;
	private TextView back_tv;
	private int userId;
	protected static final int please_auth_code_number = 0;
	protected static final int please_auth_code_wenzi = 1;
	
	private int times = MainConstants.TIMES;
	//请求随机验证码的handler
	Handler handler_random_code = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							//showToast("卡已被激活了，请换张卡片！");
							/*List<NameValuePair> params3 = new ArrayList<NameValuePair>();
							params3.add(new BasicNameValuePair("mobileNumber",phone_nubmer ));
							new DataLoader(ActivateCardActivity.this).DisplayData(MainConstants.HOST_test
									+ HttpConfigAPI.CHECK_EXIST_BY_MOBILE, params3, handler, "", false);*/
							//请求验证码的
							jsonObjectResult = JSON.parseObject(result);
							if (null != jsonObjectResult.getString("randomCode")) {
								String jsonStr = jsonObjectResult.getString("randomCode");
								createAuthCode = jsonStr;
							}
						}
					} catch (JSONException e) {
						finishProgress();
						e.printStackTrace();
					}
				} else {
					finishProgress();
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	protected JSONObject jsonObjectResult;
	//激活卡片的返回值
	Handler handler_ACTIVATE_CARD = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							//showToast("卡已被激活了，请换张卡片！");
							/*List<NameValuePair> params3 = new ArrayList<NameValuePair>();
							params3.add(new BasicNameValuePair("mobileNumber",phone_nubmer ));
							new DataLoader(ActivateCardActivity.this).DisplayData(MainConstants.HOST_test
									+ HttpConfigAPI.CHECK_EXIST_BY_MOBILE, params3, handler, "", false);*/
							//请求判断老用户（手机号）
							jsonObjectResult = JSON.parseObject(result);
							CardInfo cardInfo = jsonObjectResult.getObject("cardInfo", CardInfo.class);
							Intent intent = new Intent(ActivateCardActivity.this,ActivateCardSuccessedActivity.class);
							if(null != cardInfo.getCardNumber()&& !"".equals(cardInfo.getCardNumber())){
								intent.putExtra("cardNumber", cardInfo.getCardNumber());
							}
							if(null != cardInfo.getPointBalance()&& !"".equals(cardInfo.getPointBalance())){
								intent.putExtra("pointBalance", cardInfo.getPointBalance());
							}else {
								intent.putExtra("pointBalance","暂无");
							}
							if(null != cardInfo.getExpireTime()&& !"".equals(cardInfo.getExpireTime())){
								intent.putExtra("expireTime", cardInfo.getExpireTime());
							}else {
								intent.putExtra("expireTime", "暂无");
							}
							CardAndAccountActivity.flag = 200 ;
							startActivity(intent);
						}
					} catch (JSONException e) {
						finishProgress();
						e.printStackTrace();
					}
				} else {
					finishProgress();
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	//检验手机号是否被注册过
	Handler handler_CHECK_EXIST_BY_MOBILE = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							jsonObjectResult = JSON.parseObject(result);
							String isExist = jsonObjectResult.getString("isExist");
							if("true".equals(isExist)){//请求老用户直接激活卡片
								List<NameValuePair> params1 = new ArrayList<NameValuePair>();
								params1.add(new BasicNameValuePair("cardNumber",account_number ));
								params1.add(new BasicNameValuePair("mobileNumber",phone_nubmer ));
								new DataLoader(ActivateCardActivity.this).DisplayData(MainConstants.HOST_test
										+ HttpConfigAPI.ACTIVATE_CARD, params1, handler_ACTIVATE_CARD, "", false);
								showProgress("正在加载数据...");
							}else if("false".equals(isExist)){//新用户转到ActivateCardNextActivity
								intent.setClass(ActivateCardActivity.this, ActivateCardNextActivity.class);
								intent.putExtra("mobileNumber", phone_nubmer);
								intent.putExtra("cardNumber", account_number);
								ActivateCardActivity.this.startActivity(intent);
							}
						}
					} catch (JSONException e) {
						finishProgress();
						
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	//控制发送随机码按钮的重复发送
	Handler message_handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case please_auth_code_number:
				send_auth_code_btn.setText(times+"秒后可再次发送");
				break;

			case please_auth_code_wenzi:
				send_auth_code_btn.setText("请求验证码");
				send_auth_code_btn.setClickable(true);
				break;
			}
			super.handleMessage(msg);
		}
		
	};
	//检查卡片是否被激活
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							//卡片未被激活
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							params.add(new BasicNameValuePair("mobileNumber", phone_nubmer));
							params.add(new BasicNameValuePair("userId", userId + ""));
							params.add(new BasicNameValuePair("email", null));
							new DataLoader(ActivateCardActivity.this).DisplayData(MainConstants.HOST_test
									+ HttpConfigAPI.RANDOM_CODE, params, handler_random_code, "", false);
//							send_auth_code_btn.setClickable(false);
							/*new Handler().postDelayed(new Runnable() {
								
								@Override
								public void run() {
									// TODO Auto-generated method stub
									send_auth_code_btn.setClickable(true);
								}
							},MainConstants.TIME);*/
							send_auth_code_btn.setClickable(false);
							new Timer().schedule(new TimerTask() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									if(times > 0){
										times --;
										message_handler.sendEmptyMessage(please_auth_code_number);
										
									}else {
										message_handler.sendEmptyMessage(please_auth_code_wenzi);
										times =  MainConstants.TIMES;
										this.cancel();
									}
								}
							}, 1000, 1000);
							showProgress("正在加载数据...");
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
//							showToast("卡片已被激活、挂失或损毁");
//							{"status":false,"errorMsg":"卡片不存在"}
							jsonObjectResult = JSON.parseObject(result);
							showToast(jsonObjectResult.getString("errorMsg"));
						}
					} catch (JSONException e) { 
						
						finishProgress();
						showToast("异常"); 
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	protected void onDestroy() {
		 ProApplication.getInstance().getActivityList().remove(this);
		super.onDestroy();
	};
	
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activate_card);
		this.initBodyControlView();
		this.registerListener();
		userId = SharePrefenceUtil.getUserID(this);
		ProApplication.getInstance().getActivityList().add(this);
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.activate_card_next_btn:
			this.getControlViewText();
			if(null == account_number||"".equals(account_number)){
				showToast("卡号未输入");
			}else if(account_number.length()!=8){
				showToast("卡号必须为8位");
			}else if(null == confirm_account_number||"".equals(confirm_account_number)){
				showToast("确认卡号未输入");
			}else if(confirm_account_number.length()!=8){
				showToast("卡号必须为8位");
			}else if(StringUtil.compareString(account_number, confirm_account_number) == false){
				showToast("两次输入的卡号不一致");
			}else if(null ==phone_nubmer ||"".equals(phone_nubmer)){
				showToast("手机号未输入");
			}else if(!StringUtils.isPhoneNum(phone_nubmer)){
				showToast("请输入正确的手机号");
			}else if(null ==auth_code||"".equals(auth_code)){
				showToast("验证码未输入");
			}else if(!auth_code.equals(createAuthCode)){
				showToast("验证码错误！");
			}else{
				List<NameValuePair> params3 = new ArrayList<NameValuePair>();
				params3.add(new BasicNameValuePair("mobileNumber",phone_nubmer ));
				new DataLoader(ActivateCardActivity.this).DisplayData(MainConstants.HOST_test
						+ HttpConfigAPI.CHECK_EXIST_BY_MOBILE, params3, handler_CHECK_EXIST_BY_MOBILE, "", false);
			}
			break;
		case R.id.button_center:
			//showToast("模拟发送验证码");
			/*StringUtil stringUtil = new StringUtil();
			createAuthCode = stringUtil.createAuthCode();
			SendSmsUtil sendSmsUtil = new SendSmsUtil(this);
			sendSmsUtil.sendSms("15226160897", createAuthCode);*/
			
			this.getControlViewText();
			if(null == account_number||"".equals(account_number)){
				showToast("卡号未输入");
			}else if(account_number.length()!=8){
				showToast("卡号必须为8位");
			}else if(null == confirm_account_number||"".equals(confirm_account_number)){
				showToast("确认卡号未输入");
			}else if(confirm_account_number.length()!=8){
				showToast("卡号必须为8位");
			}else if(StringUtil.compareString(account_number, confirm_account_number) == false){
				showToast("两次输入的卡号不一致");
			}else if(null ==phone_nubmer ||"".equals(phone_nubmer)){
				showToast("手机号未输入");
			}else if(!StringUtils.isPhoneNum(phone_nubmer)){
				showToast("请输入正确的手机号");
			}
			/*if(null ==auth_code||"".equals(auth_code)){
				showToast("验证码未输入");
				flag =flag -1;
				break;
			}*/
			
			/*if(!auth_code.equals(createAuthCode)){
				showToast("验证码错误！");
				flag = flag -1;
				break;
			}*/
			else{
				List<NameValuePair> params1 = new ArrayList<NameValuePair>();
				params1.add(new BasicNameValuePair("cardNumber",account_number ));
				new DataLoader(ActivateCardActivity.this).DisplayData(MainConstants.HOST_test
						+ HttpConfigAPI.CHECK_ACTIVATION_CARD, params1, handler, "", false);
				showProgress("正在加载数据...");
			}
			break;
		case R.id.back_tv:
			this.finish();
			break;
		default:
			break;
		}
	}

	@Override
	protected void setHeaderControlViewText() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void initBodyControlView() {
		// TODO Auto-generated method stub
		activate_card_next_btn = (Button) this
				.findViewById(R.id.activate_card_next_btn);
		send_auth_code_btn = (TextView) this.findViewById(R.id.button_center);
		//卡号
		account_number_et = (EditText)this.findViewById(R.id.account_number);
		account_number_et.setHint("宽途卡号");
		/*if(null != (TextView)this.findViewById(R.id.account_title)){
			TextView account_title = (TextView)this.findViewById(R.id.account_title);
			account_title.setText("卡        号：");
		}*/
		//确认卡号
		confirm_account_number_et = (EditText)this.findViewById(R.id.confirm_account_number);
		//手机号
		phone_nubmer_et = (EditText)this.findViewById(R.id.phone_nubmer);
		//验证码
		auth_code_et = (EditText)this.findViewById(R.id.auth_code);
		back_tv = (TextView)this.findViewById(R.id.back_tv);
	}

	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void registerListener() {
		// TODO Auto-generated method stub
		activate_card_next_btn.setOnClickListener(this);
		send_auth_code_btn.setOnClickListener(this);
		back_tv.setOnClickListener(this);
	}

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub
		account_number = account_number_et.getText().toString();
		confirm_account_number = confirm_account_number_et.getText().toString();
		phone_nubmer = phone_nubmer_et.getText().toString();
		auth_code = auth_code_et.getText().toString();
	}
}
